package com.bosssoft.quickstart.demo.utils;

import java.util.regex.Pattern;

public class IDValidatorUtil {

    // 身份证号的正则表达式，18位数字或前17位数字和最后一位是数字或X
    private static final String ID_PATTERN = "^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][0-9])|(3[0-1]))\\d{3}[0-9Xx]$";

    public static boolean isValidID(String id) {
        // 验证身份证号格式
        if (!Pattern.matches(ID_PATTERN, id)) {
            return false;
        }

        // 验证校验码
        return validateCheckDigit(id);
    }


    public static boolean validateCheckDigit(String id) {
        if (id.length() != 18) {
            return false;
        }

        // 身份证前17位数字权重
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        // 校验码对应的字符
        char[] checkCode = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};

        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (id.charAt(i) - '0') * weights[i];
        }

        // 计算出的校验码
        char expectedCheckCode = checkCode[sum % 11];

        // 实际的校验码
        char actualCheckCode = id.charAt(17);

        return Character.toUpperCase(expectedCheckCode) == Character.toUpperCase(actualCheckCode);
    }

}
